/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.task;

import com.cxhd.dc.DataConfig;
import com.cxhd.dc.model.FileInfo;
import com.cxhd.dc.tool.FileUtil;
import com.cxhd.dc.tool.HttpClientUt;
import com.cxhd.dc.tool.Tools;
import com.google.common.io.Files;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author Administrator
 */
public class ParsingDicom extends BaseTask {

    private File[] fileDicomFolder;

    @Override
    public BaseTask start() {
        fileDicomFolder = new File(DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getDicomSendFolder()).listFiles();
        return this;
    }

    @Override
    public BaseTask doTask() {
        if (fileDicomFolder != null) {
            for (File file : fileDicomFolder) {
                if (file.isDirectory() && file.list().length > 0) {
                    getDicom(file);
                }
            }
        }
        return this;
    }

    @Override
    public BaseTask stop() {

        return this;
    }

    @Override
    public BaseTask cancelTask() {
        fileDicomFolder = null;
        return this;
    }

    private void getDicom(File f) {
        String device = f.getName();
        for (File fs : f.listFiles()) {
            if (fs.getName().endsWith("dcm")) {
                getDicomInfo(fs, device);
            } else {
                otherFileInfo(fs, device);
            }
        }

    }

    private void getDicomInfo(File dicom, String device) {
        makeXml(dicom, DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getRecviceXmlFolder() + dicom.getName().replace(".dcm", ".xml"), device);
    }

    public File makeXml(File file, String xmlPath, String device) {
        long startTime = System.currentTimeMillis();
        try {

            Runtime r = Runtime.getRuntime();

            Process p = r.exec("cmd.exe /c c:/cxhd2015/tools/dcm2xml.exe +fo -q +Ca latin-1 " + file.getAbsolutePath() + " " + xmlPath);
            // System.out.println("cmd.exe /c " + param + " " + absolutePath + "/" + path);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String msg = null;
            while ((msg = br.readLine()) != null) {

            }
            br.close();
            p.destroy();

            //吧XML转存到K：/reports/studyIuid/studyIuid.xml;
            checkXmlCharSet("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", xmlPath, "GBK");
            parseXml(file, xmlPath, device);

        } catch (Exception ex) {

            ex.printStackTrace();
            return null;
        }

        return new File(xmlPath);

    }

    public void checkXmlCharSet(String n, String fileLoc, String encode) {

        try {
            FileInputStream fstream = new FileInputStream(fileLoc);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in, encode));
            String strLine, contentX = "";
            int i = 0;
            boolean UTF8 = false;
            while ((strLine = br.readLine()) != null) {
                i++;
                if (i == 1) {
                    strLine = n;
                }
                if (strLine.contains("ISO_IR 192")) {
                    UTF8 = true;
                } //avoid change other coding to GBK

                if (strLine.equalsIgnoreCase("<?xml version=\1.0\"?>")) {
                    strLine = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                }
                contentX += strLine + System.getProperty("line.separator");
            }

            in.close();
            if (!UTF8) {
                FileUtil.writeText(fileLoc, contentX);
            }

        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

    }

    private void parseXml(File dicomFile, String xmlPath, String device) {
        System.out.println(xmlPath + "----------------");
        FileInfo info = new FileInfo();
        info.setType("dicom");
        try {
            SAXReader reader = new SAXReader();
            //读取文件 转换成Document
            Document document = reader.read(new File(xmlPath));
            //获取根节点元素对象
            Element root = document.getRootElement();
            Element data_set = root.element("data-set");
            List<Element> elements = data_set.elements("element");

            for (Element e : elements) {
                if (e.attributeValue("name").equalsIgnoreCase("StudyInstanceUID")) {
                    info.setStudy_iuid(e.getText());

                } else if (e.attributeValue("name").equalsIgnoreCase("PatientName")) {
                    info.setPat_name(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("PatientID")) {
                    info.setPat_id(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("PatientSex")) {
                    info.setPat_sex(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("PatientBirthDate")) {
                    info.setPat_birthdate(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("PatientAge")) {
                    info.setPat_age(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("SOPInstanceUID")) {
                    info.setSop_iuid(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("SeriesInstanceUID")) {
                    info.setSeries_iuid(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("StudyDescription")) {
                    info.setStudy_desc(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("SeriesDescription")) {
                    info.setSeries_desc(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("Modality")) {
                    info.setMods_in_study(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("StudyDate")) {
                    info.setStudy_date(e.getText());
                } else if (e.attributeValue("name").equalsIgnoreCase("StudyTime")) {
                    info.setStudy_time(e.getText());
                }
            }

            // root.getDocument()
        } catch (Exception ex) {
            System.out.println("dicom 文件解析出错 " + xmlPath);
            ex.printStackTrace();
        }
        if (checkFile(info.getSop_iuid(),dicomFile)) {
            info.setHospital_sn(device);
            info.setFile_id(uploadFileSystem(dicomFile.getAbsolutePath()));
            info.setFilePath(dicomFile.getAbsolutePath());
            info.setFileName(dicomFile.getName());
            saveData(info);
        }

    }

    private boolean checkFile(String sop_iuid,File dicomFile) {
        Record re = Db.use("atlasCenter").findFirst("select * from files where sop_iuid='" + sop_iuid + "'");
        if (re != null && re.getStr("sop_iuid") != null) {
            dicomFile.delete();
            return false;
        }
        return true;
    }

    private String uploadFileSystem(String path) {
        //System.out.println("fileserverUrl:" + DataConfig.getInstance().getAtlasFileServer());
        String file_id = HttpClientUt.postFile(path, "http://" + DataConfig.getInstance().getAtlasFileServer() + "/CXFS/upload");
        System.out.println(path + "---" + file_id);
        return file_id;
    }

    private void saveData(FileInfo info) {
        String patient_pk = null, study_pk = null, series_pk = null;
        //插入数据到patient表
        Record pat = Db.use("atlasCenter").findFirst("select * from patient where hospital_sn=? and pat_id=?", info.getHospital_sn(), info.getPat_id());
        if (pat != null && pat.get("pk") != null) {
            patient_pk = pat.get("pk") + "";

        } else {
            pat = new Record();
            pat.set("pat_name", info.getPat_name())
                    .set("pat_id", info.getPat_id())
                    .set("pat_sex", info.getPat_sex())
                    .set("pat_age", info.getPat_age())
                    .set("pat_birthdate", info.getPat_birthdate())
                    .set("hospital_sn", info.getHospital_sn())
                    .set("createtime", Tools.getDateEN());
            Db.use("atlasCenter").save("patient", "pk", pat);
            patient_pk = Db.use("atlasCenter").findFirst("SELECT LAST_INSERT_ID()").getLong("LAST_INSERT_ID()") + "";
        }

        //插入数据到study表
        Record study = Db.use("atlasCenter").findFirst("select * from study where study_iuid=? and patient_fk=?", info.getStudy_iuid(), patient_pk);
        if (study != null && study.get("pk") != null) {
            study_pk = study.get("pk") + "";
        } else {
            study = new Record();
            study.set("patient_fk", patient_pk)
                    .set("study_iuid", info.getStudy_iuid())
                    .set("study_desc", info.getStudy_desc())
                    .set("mods_in_study", info.getMods_in_study())
                    .set("createtime", Tools.getDateEN());
            Db.use("atlasCenter").save("study", "pk", study);
            study_pk = Db.use("atlasCenter").findFirst("SELECT LAST_INSERT_ID()").getLong("LAST_INSERT_ID()") + "";
        }

        //插入数据到series表
        Record series = Db.use("atlasCenter").findFirst("select * from series where series_iuid=? and study_fk=?", info.getSeries_iuid(), study_pk);
        if (series != null && series.get("pk") != null) {
            series_pk = series.get("pk") + "";
        } else {
            series = new Record();
            series.set("study_fk", study_pk)
                    .set("series_iuid", info.getSeries_iuid())
                    .set("series_desc", info.getSeries_desc())
                    .set("modality", info.getMods_in_study())
                    .set("createtime", Tools.getDateEN());
            Db.use("atlasCenter").save("series", "pk", series);
            series_pk = Db.use("atlasCenter").findFirst("SELECT LAST_INSERT_ID()").getLong("LAST_INSERT_ID()") + "";
        }

        //插入数据到files表
        Record files = Db.use("atlasCenter").findFirst("select * from files where sop_iuid=? and series_fk=?", info.getSop_iuid(), series_pk);
        if (files != null && files.get("pk") != null) {

        } else {
            files = new Record();
            files.set("type", info.getType())
                    .set("file_id", info.getFile_id())
                    .set("sop_iuid", info.getSop_iuid())
                    .set("study_iuid", info.getStudy_iuid())
                    .set("series_iuid", info.getSeries_iuid())
                    .set("series_fk", series_pk)
                    .set("filename", info.getFileName())
                    .set("createtime", Tools.getDateEN());
            Db.use("atlasCenter").save("files", "pk", files);
            //series_pk = Db.use("atlasCenter").findFirst("SELECT LAST_INSERT_ID()").getLong("LAST_INSERT_ID()") + "";
        }
        //确认文件上传完之后删除文件
        if (info.getFile_id() != null && info.getFilePath() != null) {
            new File(info.getFilePath()).delete();
        }
    }

    private void otherFileInfo(File fs, String device) {
        String type = Files.getFileExtension(fs.getName());
        String uuid = null;
        if ("sql".equalsIgnoreCase(type)) {
            uuid = Files.getNameWithoutExtension(fs.getName());
        } else if ("rpt".equalsIgnoreCase(type)) {
            uuid = fs.getName().replaceFirst("-", "_").replaceFirst("-", "_").split("_")[1];
        }
        FileInfo info = new FileInfo();
        info.setType(type);
        info.setFile_id(uploadFileSystem(fs.getAbsolutePath()));
        info.setStudy_iuid(uuid);
        info.setFileName(fs.getName());
        info.setFilePath(fs.getAbsolutePath());

        Record files = new Record();
        files.set("type", info.getType())
                .set("file_id", info.getFile_id())
                .set("study_iuid", info.getStudy_iuid())
                .set("filename", info.getFileName())
                .set("createtime", Tools.getDateEN());
        Db.use("atlasCenter").save("files", "pk", files);
        if (info.getFile_id() != null && info.getFilePath() != null) {
            new File(info.getFilePath()).delete();
        }
    }

}
